package com.quectel.mobile.controller.notice;

import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.core.module.notice.dto.NoticeActivityOutlinkDto;
import com.quectel.core.module.notice.dto.NoticeDto;
import com.quectel.core.module.notice.service.NoticeActivityOutlinkService;
import com.quectel.core.module.notice.service.NoticeService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.mobile.controller.BaseController;
import com.quectel.mobile.interceptor.LoginMobileUserSession;
import com.quectel.mobile.util.SessionHolder;
import com.quectel.mobile.vo.notice.NoticeActivityVo;
import com.quectel.mobile.vo.notice.NoticeSimplifyVo;
import com.quectel.sys.module.sys.service.SysCodeService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import com.quectel.util.kit.Snowflake;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author yubobo
 * @email bobo.yu@quectel.com
 * @date 2021/12/23 3:50 下午
 */
@RestController
@RequestMapping("notice")
@Tag(name = "NoticeController", description = "移动端公告相关api")
public class NoticeController extends BaseController {

    public static final String NOTICE_CATEGORY = "noticeCategory";
    public static final String STATUS = "status";

    @DubboReference
    private NoticeService noticeService;
    @DubboReference
    private SysCodeService sysCodeService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private NoticeActivityOutlinkService activityOutlinkService;

    @GetMapping("list")
    @Operation(summary = "移动端公告的分页查询列表")
    public Response<Page<NoticeSimplifyVo>> list(
            @Parameter(description = "传入公告类型 noticeCategory 1.物业通知 2.社区活动 3.社区党建") @RequestParam Map<String, Object> params) {
        params.put(STATUS, 1);
        Request request = Request.configParams(params);
        Long villageId = request.getLong("villageId");
        VillageDto villageDto = villageService.selectCacheById(villageId);
        if (villageDto != null) {
            params.put(LambdaUtil.getFieldName(NoticeDto::getTenantId), villageDto.getTenantId());
        }

        int totalCount = noticeService.queryTotal(request.getParams());
        List<NoticeDto> list = null;
        List<NoticeSimplifyVo> resultList = null;
        if (totalCount > 0) {
            list = noticeService.queryList(params);
            resultList = CopyUtils.copyList(list, NoticeSimplifyVo.class);
        } else {
            resultList = new ArrayList<>();
        }
        Page<NoticeSimplifyVo> page = new Page<>(request.getPageNo(), request.getPageSize(), totalCount, resultList);
        return Response.<Page<NoticeSimplifyVo>>ok().wrap(page);
    }

    @GetMapping("findById")
    @Operation(summary = "根据条件获取公告详情")
    public Response<NoticeDto> findById(@Parameter(description = "公告id") @RequestParam(required = false) Long id) {
        NoticeDto noticeDto = noticeService.selectCacheById(id);
        return Response.<NoticeDto>ok().wrap(noticeDto);
    }

    @PostMapping("signUp")
    @Operation(summary = "报名操作")
    public Response<Object> signUp(@RequestBody NoticeActivityVo vo) {
        LoginMobileUserSession loginMobileUserSession = SessionHolder.getLoginMobileUserSession();

        String phone = vo.getPhone();
        Long noticeId = vo.getNoticeId();
        String name = vo.getName();
        if (StringUtils.isEmpty(phone) || noticeId.equals("") || StringUtils.isEmpty(name)) {
            return Response.error("缺少必填参数");
        }

        NoticeDto noticeDto = noticeService.selectCacheById(noticeId);
        boolean effectiveDate = isEffectiveDate(new Date(), noticeDto.getStartTime(), noticeDto.getEndTime());

        if (effectiveDate) {
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("phone", phone);
            objectMap.put("activityId", noticeId);
            int total = activityOutlinkService.queryTotal(objectMap);
            if (total > 0) {
                return Response.ok().wrap("您报名参与过该活动了");
            } else {
                NoticeActivityOutlinkDto dto = new NoticeActivityOutlinkDto();
                dto.setId(Snowflake.nextId());
                dto.setCreateTime(new Date());
                dto.setName(name);
                dto.setPhone(phone);
                dto.setActivityId(noticeId);
                activityOutlinkService.save(dto);
            }
            return Response.ok().wrap("投票成功");
        } else {
            return Response.ok().wrap("报名事件已过期或未开始");
        }
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param nowTime   当前时间
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return true 在区间  false 不在区间
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }
}